
package com.yunfei.api.smrzUser;

import com.yunfei.api.smrz.bo.AppFileBo;
import com.yunfei.api.smrz.bo.AppFileSimpleBo;
import com.yunfei.bo.crmAcceDtl.CrmAcceDtlBo;
import com.yunfei.bo.result.ResultModel;
import com.yunfei.bo.smrz.*;
import com.yunfei.entity.TPersonalUserEntity;
import com.yunfei.entity.TblobstorageEntity;
import com.yunfei.entity.crmAcceDtl.CrmAcceDtlEntity;
import com.yunfei.enums.ResultStatus;
import com.yunfei.enums.ShiMingRenZhengStatus;
import com.yunfei.mapper.aiiidb.*;
import com.yunfei.mapper.crm.ShiMingRenZhengFileMapper;
import com.yunfei.mapper.crm.TblobtSorageMapper;
import com.yunfei.service.ShiMingRenZhengService;
import com.yunfei.utils.TokenUtil;
import com.yunfei.utils.idcard.AccountValidatorUtil;
import com.yunfei.utils.idcard.IDCardUtil;
import com.yunfei.utils.idcard.SmrzUtils;
import com.yunfei.utils.json.JsonListUtil;
import com.yunfei.utils.procedure.NewUserProcedure;
import com.yunfei.utils.procedure.ShiMingRenZhengProcedure;
import com.yunfei.utils.procedure.ShiMingRenZhengProcedureReturnInfo;
import com.yunfei.utils.string.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 实名认证接口-客户
 * @Author: zhengyunfei
 * @Date: 2018/6/15
 * @time:11:26
 */
@SuppressWarnings("ALL")
@Api(value = "获取所有证件类型",tags = "获取所有证件类型")
@RestController
@RequestMapping("/api/user/smrz")
public class ShiMingRenZhengUserApiController {
    @Autowired
    private ShiMingRenZhengMapper shiMingRenZhengMapper;
    @Autowired
    private ShiMingRenZhengService shiMingRenZhengService;
    @Autowired
    private TPersonalUserMapper tPersonalUserMapper;
    @Autowired
    private MessageMapper messageMapper ;
    @Autowired
    private CrmAcceDtlMapper crmAcceDtlMapper;
    @Autowired
    private ShiMingRenZhengFileMapper shiMingRenZhengFileMapper;
    @Autowired
    private ShiMingRenZhengUploadMapper shiMingRenZhengUploadMapper;
    @Autowired
    private TblobtSorageMapper tblobtSorageMapper;
    /**
    * @Description: 获取所有证件类型
    * @Author: zhengyunfei
    * @Date: 2019/1/11
    * @time:17:00
    */
    @GetMapping("/getCardType")
    @ApiOperation(value = "获取所有证件类型",notes = "获取所有证件类型",position = 1,response = Object.class)
    public Object getAllCardType(){
        ResultModel resultModel=new ResultModel();
        List<IdCardType> idCardTypeList=shiMingRenZhengMapper.getCardType(null);
        resultModel.setCode(ResultStatus.SUCCESS.getCode());
        resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
        resultModel.setData(idCardTypeList);
        return resultModel;
    }
    /**
     * @Description: 根据手机号码判断手机号是否在crm已经实名认证
     * 如果手机号在crm对应的客户已经进行了实名认证，无需实名认证
     * 判断手机号是否在crm已经实名认证：
     * 如果下面的sql结果大于0，已实名认证，无需进行实名认证
     * @Author: zhengyunfei
     * @Date: 2019/1/11
     * @time:17:00
     */
    @PostMapping("/save")
    @ApiOperation(value = "实名认证",notes = "实名认证",position = 1,response = Object.class)
    public Object save(IdCardBo idCardBo){
        ResultModel resultModel=new ResultModel();
       // try{
            //参数格式校验
            String cardType=idCardBo.getCardType();//证件类型
            String cardNo=idCardBo.getCardNo();//证件号码
            String mobile=idCardBo.getMobile();//手机号
            String userName=idCardBo.getUserName();
            String token=idCardBo.getToken();
            String userId= TokenUtil.getInstance().getUserId(token);
            if(StringUtil.isNullOrEmpty(mobile)){
                TPersonalUserEntity userEntity=tPersonalUserMapper.findById(idCardBo.getcCustNo());
                if(!StringUtil.isNullOrEmpty(userEntity)){
                    mobile=userEntity.getMobile();
                    idCardBo.setMobile(mobile);
                }

            }
            if (validParamMethod(resultModel, cardType, cardNo)) return resultModel;
        //调用实名认证接口
        SmrzBo result= SmrzUtils.getResult(userName,cardNo);
        if(!result.getStatus().equals("01")){
            //更新实名认证结果为不通过
            //shiMingRenZhengMapper.updateSmrzStatusWeiRenZheng(paramMap);
            //shiMingRenZhengMapper.updateSmrzStatusBuTongGuo(paramMap);
            resultModel.setCode(ResultStatus.SHIMINGRENZHENG_ERROR.getCode());
            resultModel.setMessage(result.getMsg());
            return resultModel;
        }
        System.out.println("实名认证结果================"+result);
            boolean isShiMingRenZhengFlg=false;//实名认证标识
            /**
             第一步:
             如果手机号在crm对应的客户已经进行了实名认证，无需实名认证
             判断手机号是否在crm已经实名认证：
             如果下面的sql结果大于0，已实名认证，无需进行实名认证
             **/
            Map<String,Object> mobileMap=new HashMap<>();
            mobileMap.put("mobile",mobile);
            int crmSmrzCount=(Integer) shiMingRenZhengMapper.getCrmSmrz(mobileMap);
           //int count2=shiMingRenZhengBo.getIsRenZheng();
            if(crmSmrzCount>0){
                isShiMingRenZhengFlg=true;
            }else{
                /**第二步：如果不满足第一步，判断是否存在相同证件号：
                 判断手机号是否在crm已经实名认证：
                 如果下面的sql结果大于0，已实名认证，但手机号与crm不一致。
                 提示“该证件号已经实名认证，但手机号与实名认证手机号不相符，我们将尽快联系对应理财师
                 **/
                Map<String,Object> queryMap=new HashMap<>();
                queryMap.put("cIdentityType",idCardBo.getCardType());
                queryMap.put("cIdentityNo",idCardBo.getCardNo());
                int count=shiMingRenZhengMapper.isEqualCardNo(queryMap);
                if(count>0){
                    isShiMingRenZhengFlg=true;
                    resultModel.setMessage(ShiMingRenZhengStatus.SHI_MING_REN_ZHENG_STATUS.getMessage());
                    resultModel.setCode(ShiMingRenZhengStatus.SHI_MING_REN_ZHENG_STATUS.getCode());
                    return resultModel;
                }else{
                    //新客户
                    //插入推送表
                    // messageMapper.addMessage(idCardBo);
                    //新建实名认证
                    Connection con = shiMingRenZhengService.getConnection();
                    //新建客户
                    NewUserProcedure newUserProcedure=new NewUserProcedure();
                    ShiMingRenZhengProcedureReturnInfo newUserReturenInfo= newUserProcedure.save(idCardBo,con);
                    String custNo=newUserReturenInfo.getpReasonInfo();
                    resultModel.setData(custNo);
                    idCardBo.setcCustNo(custNo);
                    ShiMingRenZhengProcedure shiMingRenZhengProcedure=new ShiMingRenZhengProcedure();
                    ShiMingRenZhengProcedureReturnInfo returnInfo=shiMingRenZhengProcedure.save(idCardBo,con);
                    //更新实名认证结果通过
                    Map<String,Object> paramMap=new HashMap<>();
                    paramMap.put("cCustNo",custNo);
                    paramMap.put("cCustName",userName);
                    shiMingRenZhengMapper.updateSmrzStatusYiRenZheng(paramMap);
                    //插入T_PERSON_USER的客户填写的证件类型和证件号码
                    TPersonalUserEntity tPersonalUserEntity=new TPersonalUserEntity();
                    tPersonalUserEntity.setUserId(userId);
                    tPersonalUserEntity.setIdenType(cardType);
                    tPersonalUserEntity.setIdenNo(cardNo);
                    tPersonalUserMapper.update(tPersonalUserEntity);
                    resultModel.setCode(ResultStatus.SUCCESS.getCode());
                    resultModel.setMessage(ResultStatus.SUCCESS.getMessage());

                }
            }

      /*  }catch (Exception e){
            e.printStackTrace();
        }*/


        return resultModel;
    }
    /**
     * @Description: 实名认证编辑，只允许编辑证件号，证件类型，附件
     * @Author: zhengyunfei
     * @Date: 2019/3/8
     * @time:10:40
     */
    @PostMapping(value = "/update",produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "实名认证编辑",notes = "实名认证(理财师发起)",position = 1,response = Object.class)
    public Object isShiMingRenZhengByMobile(IdCardBo idCardBo, HttpServletRequest request, String imagJson){
        ResultModel resultModel=new ResultModel();
        Map<String,Object> queryMap=new HashMap<>();
        System.out.println("imgJson=========="+imagJson);
        List<AppFileSimpleBo> imgList= JsonListUtil.jsonToList(imagJson,AppFileSimpleBo.class);
        List<AppFileSimpleBo> notDeleteImage=new ArrayList<>();
        //参数格式校验
        String userName=idCardBo.getUserName();
        String cardType=idCardBo.getCardType();//证件类型
        String cardNo=idCardBo.getCardNo();//证件号码
        String cCustNo=idCardBo.getcCustNo();
        String token=idCardBo.getToken();
        String currentUserId=TokenUtil.getInstance().getUserId(token);
        if (shiMingRenZhengService.validParamMethod(resultModel,idCardBo)) return resultModel;
        //调用实名认证接口
        SmrzBo result= SmrzUtils.getResult(userName,cardNo);
        if(!result.getStatus().equals("01")){
            //更新实名认证结果为不通过
            //shiMingRenZhengMapper.updateSmrzStatusWeiRenZheng(paramMap);
            //shiMingRenZhengMapper.updateSmrzStatusBuTongGuo(paramMap);
            resultModel.setCode(ResultStatus.SHIMINGRENZHENG_ERROR.getCode());
            resultModel.setMessage(result.getMsg());
            return resultModel;
        }
        System.out.println("实名认证结果================"+result);
        Connection con = shiMingRenZhengService.getConnection();
        ShiMingRenZhengProcedure shiMingRenZhengProcedure=new ShiMingRenZhengProcedure();
        queryMap.put("cCustNo",cCustNo);
        XuLieHaoBao xuLieHaoBao= (XuLieHaoBao) shiMingRenZhengMapper.getPserilNo(queryMap);//序列号
        String pSerilNo=xuLieHaoBao.getlSerialNo();
        ShiMingRenZhengProcedureReturnInfo returnInfo=shiMingRenZhengProcedure.update(pSerilNo,idCardBo,con);
       // shiMingRenZhengService.updateSmrzStatus(resultModel, cCustNo,userName);
        Map<String,Object> paramMap=new HashMap<>();
        paramMap.put("cCustNo",cCustNo);
        paramMap.put("cCustName",userName);
        //更新实名认证结果通过
        shiMingRenZhengMapper.updateSmrzStatusYiRenZheng(paramMap);
        resultModel.setCode(ResultStatus.SUCCESS.getCode());
        resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
        //插入T_PERSON_USER的客户填写的证件类型和证件号码
        TPersonalUserEntity tPersonalUserEntity=new TPersonalUserEntity();
        tPersonalUserEntity.setUserId(currentUserId);
        tPersonalUserEntity.setIdenType(cardType);
        tPersonalUserEntity.setIdenNo(cardNo);
        tPersonalUserMapper.update(tPersonalUserEntity);

        String reasonCode=returnInfo.getpReasonCode();
        queryMap.put("smrzResult",returnInfo);
        boolean isDeleteFirstFlg=false;
        //处理附件
        for(int i=0;i<imgList.size();i++){
            boolean isDelete=imgList.get(i).isDelete();
            String cCatalog=imgList.get(i).getcCatalog();
            if("TCUSTREGISTERREQ_MAIN".equals(cCatalog)){
                isDeleteFirstFlg=imgList.get(i).isDelete();
            }
            if(isDelete){
                //删除app附件
                Map<String,Object> acceDtlMap=new HashMap<>();
                acceDtlMap.put("lStorageid",imgList.get(i).getlStorageId());
                //删除app附件
                crmAcceDtlMapper.deleteByMap(acceDtlMap);
                crmAcceDtlMapper.deleteOldTblobStorageFileByMap(acceDtlMap);
                //删除crm附件
                shiMingRenZhengFileMapper.deleteOldFileByMap(acceDtlMap);
            }else{
                notDeleteImage.add(imgList.get(i));
            }
        }
        //如果第一张被删除了，才处理实名认证第一张图片
        if(isDeleteFirstFlg){
            for(int i=0;i<notDeleteImage.size();i++){
                if(i==0){
                    AppFileBo appFileBo=new AppFileBo();
                    //将未删除的第一张变为首张
                    Map<String, Object> crmAcceDtlQueryMap=new HashMap<>();
                    String cSubkeyId=notDeleteImage.get(0).getcSubkeyId();
                    String oLstorageId=notDeleteImage.get(0).getlStorageId();
                    appFileBo.setcSubkeyId(cSubkeyId);
                    String lStrorageId=shiMingRenZhengUploadMapper.getLstrorageId(appFileBo);
                    crmAcceDtlQueryMap.put("lStorageid",lStrorageId);
                    CrmAcceDtlEntity crmAcceDtlEntity= (CrmAcceDtlEntity) crmAcceDtlMapper.get(crmAcceDtlQueryMap);
                    TblobstorageEntity tblobstorageEntity=crmAcceDtlMapper.getTblobstorage(crmAcceDtlQueryMap);
                    appFileBo.setlStorageid(oLstorageId);
                    appFileBo.setlStorageidFirst(lStrorageId);
                    appFileBo.setcCataLog("TCUSTREGISTERREQ_MAIN");
                    appFileBo.setFileUrl(notDeleteImage.get(i).getFileUrl());
                    if(!StringUtil.isNullOrEmpty(tblobstorageEntity)){
                        appFileBo.setUserId(tblobstorageEntity.getcCreator());
                        appFileBo.setcFileSize(tblobstorageEntity.getlFilesize());
                        appFileBo.setcFilename(tblobstorageEntity.getcFilename());
                    }
                    Map<String,Object> deptNodeCodeQuerMap=new HashMap<>();
                    String userId=appFileBo.getUserId();
                    if(StringUtil.isNullOrEmpty(userId)){
                        userId="";
                    }
                    deptNodeCodeQuerMap.put("userId",userId);
                    String deptNodeCode=shiMingRenZhengUploadMapper.getDeptNodeCode(deptNodeCodeQuerMap);
                    if(StringUtil.isNullOrEmpty(deptNodeCode)){
                        deptNodeCode="";
                    }
                    appFileBo.setDeptNodeCode(deptNodeCode);
                    //判断第一张的是否被删除，如果第一张的被删除了，则需要将现在的第一张变更为首张，否则不用管
                    shiMingRenZhengUploadMapper.updateFirst(appFileBo);
                    if(StringUtil.isNullOrEmpty(crmAcceDtlEntity)){
                        //保存文件附件到app数据库
                        CrmAcceDtlBo crmAcceDtlBo = new CrmAcceDtlBo();
                        crmAcceDtlBo.setLStorageid(lStrorageId);
                        crmAcceDtlBo.setFileUrl(appFileBo.getFileUrl());
                        crmAcceDtlMapper.add(crmAcceDtlBo);
                    }
            /*   else{
                   shiMingRenZhengUploadMapper.updateFirst(appFileBo);
               }*/
                    //保存文件到crm
                    tblobstorageEntity.setcNodecode(deptNodeCode);
                    tblobstorageEntity.setcFilename(crmAcceDtlEntity.getCFilename());
                    tblobstorageEntity.setlFilesize(tblobstorageEntity.getlFilesize());
                    tblobtSorageMapper.add(tblobstorageEntity);
                    //delete crm表
                    crmAcceDtlMapper.deleteByMap(crmAcceDtlQueryMap);
                    crmAcceDtlMapper.deleteOldTblobStorageFileByMap(crmAcceDtlQueryMap);
                    shiMingRenZhengFileMapper.deleteOldFileByMap(crmAcceDtlQueryMap);
                }
            }
        }
        return resultModel;
    }
    /**
    * @Description: 实名认证参数校验
    * @Param: [resultModel, cardType, cardNo]
    * @return: boolean
    * @Author: zhengyunfei
    * @Date: 2019/1/16
    * @time:13:28
    */
    private boolean validParamMethod(ResultModel resultModel, String cardType, String cardNo) {
        //校验规则中国护照 9位  1个字母+8个数字   港澳通行证：9位，1个字母+8个数字   台胞证号是8位数字     国外人永久居留证：15位，前三位是字母
        if("0".equals(cardType)){//身份证
            String errorMsg= IDCardUtil.IDCardValidate(cardNo);
            if(!StringUtil.isNullOrEmpty(errorMsg)){
                //身份证格式错误
                resultModel.setMessage(errorMsg);
                resultModel.setCode(ShiMingRenZhengStatus.IDCARD_NO_ERROR.getCode());
                return true;
            }
        }
        if("1".equals(cardType)){//中国护照
            boolean isHuZhao= AccountValidatorUtil.isHuZhao(cardNo);
            if(!isHuZhao){
                resultModel.setMessage(ShiMingRenZhengStatus.HUZHAO_NO_ERROR.getMessage());
                resultModel.setCode(ShiMingRenZhengStatus.HUZHAO_NO_ERROR.getCode());
                return true;
            }
        }
        if("A".equals(cardType)){//港澳通行证
            boolean isGangAoTongXingZheng=AccountValidatorUtil.isGangAoTongXingZheng(cardNo);
            if(!isGangAoTongXingZheng){
                resultModel.setMessage(ShiMingRenZhengStatus.GANGAOTONGXINGZHENG_NO_ERROR.getMessage());
                resultModel.setCode(ShiMingRenZhengStatus.GANGAOTONGXINGZHENG_NO_ERROR.getCode());
                return true;
            }

        }
        if("D".equals(cardType)){//台胞证
            boolean isTaiBaoZheng=AccountValidatorUtil.isTaiBaoZheng(cardNo);
            if(!isTaiBaoZheng){
                resultModel.setMessage(ShiMingRenZhengStatus.TAIBAOZHENG_ERROR.getMessage());
                resultModel.setCode(ShiMingRenZhengStatus.TAIBAOZHENG_ERROR.getCode());
                return true;
            }
        }
        if("J".equals(cardType)){//国外人永久居留证
            boolean isGaiWaiJuZhuZheng=AccountValidatorUtil.isGuoWaiJuZhuZheng(cardNo);
            if(!isGaiWaiJuZhuZheng){
                resultModel.setMessage(ShiMingRenZhengStatus.GAOWAIJUZHUZHENG_ERROR.getMessage());
                resultModel.setCode(ShiMingRenZhengStatus.GAOWAIJUZHUZHENG_ERROR.getCode());
                return true;
            }
        }
        if("7".equals(cardType)){//其他

        }
        return false;
    }
}
